extends Area2D
@onready var npc: Area2D = $"."
@onready var collision_shape_2d: CollisionShape2D = $CollisionShape2D
@onready var animated_sprite_2d: AnimatedSprite2D = $AnimatedSprite2D
@onready var grid_container: GridContainer = $GridContainer
@onready var label: Label = $GridContainer/Label
@onready var label_2: Label = $GridContainer/Label2
var my_position = 0
var image_name = ""
var my_image: Image
var npc_data
signal click_npc(id: int)
func setImage(id: float) -> void:
	npc_data = NpcUtil.get_npc_for_id(id)
	image_name="stand_"+str(int(npc_data["direction"]))
	var sprite_frames = load(ResourceUtil.load_animation(npc_data["skin"]))
	animated_sprite_2d.sprite_frames = sprite_frames
	animated_sprite_2d.sprite_frames.set_animation_loop(image_name, true)
	animated_sprite_2d.play(image_name)
	if npc_data["title"].is_empty():
		label.visible=false
	else:
		label.text=npc_data["title"]
	label_2.text=npc_data["name"]
	my_image = animated_sprite_2d.sprite_frames.get_frame_texture(image_name, 0).get_image()
	var aaa = RectangleShape2D.new()
	aaa.size=Vector2(my_image.get_width(), my_image.get_height())
	collision_shape_2d.shape=aaa
	grid_container.position.y=my_image.get_height()/2
	label.add_theme_color_override("font_color", ColorUtil.Color_45)
	label_2.add_theme_color_override("font_color", ColorUtil.Color_33)

func _on_input_event(viewport: Node, event: InputEvent, shape_idx: int) -> void:
	var target_position = get_local_mouse_position()
	var aaa = target_position+Vector2(my_image.get_width()/2, my_image.get_height()/2)
	var bbb = my_image.get_pixelv(aaa)
	if bbb.r!=0 ||  bbb.g!=0 ||  bbb.b!=0:
		if event is InputEventMouseButton:
			if event.is_pressed() and event.button_index ==  MouseButton.MOUSE_BUTTON_LEFT:
				emit_signal("click_npc",npc_data["id"])

func _on_animated_sprite_2d_animation_looped() -> void:
	my_position = 0

func _on_animated_sprite_2d_animation_changed() -> void:
	my_image = animated_sprite_2d.sprite_frames.get_frame_texture(image_name, my_position).get_image()
	my_position += 1
